<template>
  <h2>我的文章列表</h2>
  <div class="list-group" v-if="articleList">
    <div class="list-group-item list-group-item-action" v-for="article in articleList" :key="article.id">
      <div class="d-flex w-100 justify-content-between">
        <h5 class="mb-1">{{ article.title }}</h5>
        <small class="text-muted">更新时间：{{ useDayjs(article.updatetime).format('YYYY-MM-DD hh:mm:ss') }}</small>
      </div>
      <p class="mb-1">{{ article.content }}</p>
      <div class="btn-group" role="group" aria-label="Basic example">
        <button type="button" class="btn btn-primary btn-sm" @click="handleDetail(article.id)">查看详情</button>
        <button type="button" class="btn btn-success btn-sm" @click="handleEdit(article.id)">编辑</button>
        <button type="button" class="btn btn-danger btn-sm" @click="handleDelete(article.id)">删除</button>
      </div>
    </div>
  </div>
  <Modal :visible="modalVisible" @modal-cancel="cancelModal" @modal-confirm="confirmModal" title="删除文章提示">
    <span>亲，确定删除这篇文章？</span>
  </Modal>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, ref } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import Modal from '../components/Modal.vue';
import dayjs from 'dayjs';
export default defineComponent({
  name: 'articleList',
  components: { Modal },
  setup() {
    const store = useStore();
    const router = useRouter();
    const modalVisible = ref(false);
    const deleteArticleId = ref('');
    const useDayjs = (time: string) => dayjs(time);
    onMounted(() => {
      store.dispatch('fetchArticleList');
    });
    const articleList = computed(() => store.getters.getPosts());
    const handleDetail = (id: string) => {
      router.push({
        name: 'article',
        params: { id }
      });
    };
    const handleEdit = (id: string) => {
      router.push({
        name: 'create',
        query: { id }
      });
    };
    const handleDelete = (id: string) => {
      modalVisible.value = true;
      deleteArticleId.value = id;
    };
    const cancelModal = () => {
      modalVisible.value = false;
    };
    const confirmModal = () => {
      modalVisible.value = false;
      store.dispatch('fetchDeleteArticle', deleteArticleId.value).then(list => {
        if (list.code === 0) {
          store.dispatch('fetchArticleList');
        }
      });
    };

    return { articleList, modalVisible, handleDetail, handleEdit, handleDelete, cancelModal, confirmModal, useDayjs };
  }
});
</script>

<style></style>
